package com.hzit.proxy.user;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzit.net.WXNetUtil;
import com.hzit.proxy.base.AccessToken;
import com.hzit.proxy.entity.UserEntity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserInfoProxy {


    /**
     * 获取用户详情列表  最大100个
     *
     * @param openIds
     * @return
     */
    public List<UserEntity> getUserListInfo(List<String> openIds) {

        String url = "https://api.weixin.qq.com/cgi-bin/user/info/batchget?access_token=" + AccessToken.getToken();

        //1.封装参数
        String initParam = this.initParam(openIds);

        //2.获取内容
        String result = WXNetUtil.post(url, initParam);

        //3.解析详情
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.containsKey("user_info_list")) {

            JSONArray jsonArray = jsonObject.getJSONArray("user_info_list");

            List<UserEntity> userEntityList = jsonArray.toJavaList(UserEntity.class);
            return userEntityList;

        }

        System.out.println("获取用户详情:" + result);

        return null;
    }


    /**
     * 封装用户详情参数
     *
     * @param list
     * @return
     */
    private String initParam(List<String> list) {
        //{
        //    "user_list": [
        //        {
        //            "openid": "otvxTs4dckWG7imySrJd6jSi0CWE",
        //            "lang": "zh_CN"
        //        },
        //        {
        //            "openid": "otvxTs_JZ6SEiP0imdhpi50fuSZg",
        //            "lang": "zh_CN"
        //        }
        //    ]
        //}
        Map<String, List<Map<String, String>>> paramMap = new HashMap<>();

        List<Map<String, String>> userList = new ArrayList<>();

        for (String openId : list) {
            Map<String, String> map = new HashMap<>();
            map.put("lang", "zh_CN");
            map.put("openid", openId);

            userList.add(map);
        }

        paramMap.put("user_list", userList);


        String param = JSONObject.toJSONString(paramMap);
        System.out.println(param);
        return param;
    }

}
